#include "aodv.h"
#include "aodv_types.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 定时器最大数量
#define MAX_TIMERS 50

// 定时器全局变量
static timer_t timers[MAX_TIMERS];
static int timer_count = 0;
static int next_timer_id = 1;

// 创建定时器
int timer_create(timer_type_t type, uint32_t timeout, void *data) {
    if (timer_count >= MAX_TIMERS) {
        printf("Too many timers created\n");
        return -1;
    }
    
    // 找到一个可用的定时器槽
    int timer_id = next_timer_id++;
    int slot_index = timer_count;
    
    // 初始化定时器
    timers[slot_index].type = type;
    timers[slot_index].timeout = get_current_time() + timeout;
    timers[slot_index].data = data;
    timers[slot_index].active = 0; // 默认不激活
    
    timer_count++;
    
    printf("Created timer %d, type: %d, timeout: %u ms\n", 
           timer_id, type, timeout);
    
    return timer_id;
}

// 启动定时器
int timer_start(int timer_id) {
    for (int i = 0; i < timer_count; i++) {
        // 这里简化处理，使用索引作为ID
        if (i + 1 == timer_id) { // 假设ID是从1开始的索引
            timers[i].active = 1;
            printf("Started timer %d\n", timer_id);
            return 0;
        }
    }
    return -1; // 定时器不存在
}

// 停止定时器
int timer_stop(int timer_id) {
    for (int i = 0; i < timer_count; i++) {
        if (i + 1 == timer_id) {
            timers[i].active = 0;
            printf("Stopped timer %d\n", timer_id);
            return 0;
        }
    }
    return -1; // 定时器不存在
}

// 重启定时器
int timer_restart(int timer_id, uint32_t new_timeout) {
    for (int i = 0; i < timer_count; i++) {
        if (i + 1 == timer_id) {
            timers[i].timeout = get_current_time() + new_timeout;
            timers[i].active = 1;
            printf("Restarted timer %d with new timeout: %u ms\n", 
                   timer_id, new_timeout);
            return 0;
        }
    }
    return -1; // 定时器不存在
}

// 处理超时的定时器回调函数类型
typedef void (*timer_callback_t)(timer_t *timer);

// RREQ超时处理
static void handle_rreq_timeout(timer_t *timer) {
    uint32_t *dest_ip = (uint32_t *)timer->data;
    printf("RREQ timeout for destination: %d.%d.%d.%d\n",
           ((*dest_ip) >> 24) & 0xFF, ((*dest_ip) >> 16) & 0xFF, 
           ((*dest_ip) >> 8) & 0xFF, (*dest_ip) & 0xFF);
    
    // 检查是否需要重新发起路由发现
    route_table_entry_t *entry = route_table_find(*dest_ip);
    if (entry != NULL && entry->rreq_retries < aodv_get_config()->max_rreq_retries) {
        entry->rreq_retries++;
        printf("Retrying route discovery for destination: %d.%d.%d.%d, retry count: %d\n",
               ((*dest_ip) >> 24) & 0xFF, ((*dest_ip) >> 16) & 0xFF, 
               ((*dest_ip) >> 8) & 0xFF, (*dest_ip) & 0xFF,
               entry->rreq_retries);
        
        // 重新发起路由发现
        initiate_route_discovery(*dest_ip);
    } else {
        printf("Maximum RREQ retries reached for destination: %d.%d.%d.%d\n",
               ((*dest_ip) >> 24) & 0xFF, ((*dest_ip) >> 16) & 0xFF, 
               ((*dest_ip) >> 8) & 0xFF, (*dest_ip) & 0xFF);
        
        // 删除路由表项
        route_table_delete(*dest_ip);
    }
}

// 路由过期处理
static void handle_route_expiration(timer_t *timer) {
    uint32_t *dest_ip = (uint32_t *)timer->data;
    printf("Route expired for destination: %d.%d.%d.%d\n",
           ((*dest_ip) >> 24) & 0xFF, ((*dest_ip) >> 16) & 0xFF, 
           ((*dest_ip) >> 8) & 0xFF, (*dest_ip) & 0xFF);
    
    // 使路由无效
    route_table_invalidate(*dest_ip);
}

// HELLO定时器处理
static void handle_hello_timer(timer_t *timer) {
    // 发送HELLO消息
    send_hello_message();
    
    // 重启HELLO定时器
    aodv_config_t *config = aodv_get_config();
    if (config) {
        timer_restart(1, config->hello_interval); // 假设HELLO定时器ID为1
    }
}

// 邻居过期处理
static void handle_neighbor_expiration(timer_t *timer) {
    uint32_t *neighbor_ip = (uint32_t *)timer->data;
    printf("Neighbor expiration timer triggered for: %d.%d.%d.%d\n",
           ((*neighbor_ip) >> 24) & 0xFF, ((*neighbor_ip) >> 16) & 0xFF, 
           ((*neighbor_ip) >> 8) & 0xFF, (*neighbor_ip) & 0xFF);
    
    // 检查邻居状态
    check_neighbor_status();
}

// 定时器处理函数表
static timer_callback_t timer_callbacks[] = {
    handle_rreq_timeout,       // TIMER_RREQ_TIMEOUT
    NULL,                      // TIMER_RREP_TIMEOUT (暂未实现)
    handle_route_expiration,   // TIMER_ROUTE_EXPIRATION
    handle_hello_timer,        // TIMER_HELLO
    handle_neighbor_expiration // TIMER_NEIGHBOR_EXPIRATION
};

// 处理所有定时器
void process_timers(void) {
    uint32_t current_time = get_current_time();
    
    for (int i = 0; i < timer_count; i++) {
        if (timers[i].active && current_time >= timers[i].timeout) {
            printf("Timer %d triggered, type: %d\n", i + 1, timers[i].type);
            
            // 调用相应的定时器处理函数
            if (timers[i].type >= 0 && timers[i].type < sizeof(timer_callbacks) / sizeof(timer_callback_t)) {
                timer_callback_t callback = timer_callbacks[timers[i].type];
                if (callback != NULL) {
                    callback(&timers[i]);
                }
            }
            
            // 定时器触发后自动停用
            timers[i].active = 0;
        }
    }
}